var userinfo = uniCloud.importObject('userinfo');
var md5 = userinfo.md5('fdfdfdfdf');
console.log('md4', md5);


const db = uniCloud.database();
// 导航
const navigatorMenu = function() {
	return new Promise((resolve, reject) => {
		db.collection('navigator-menu').orderBy('sort asc').get().then(res => {
			resolve(res.result);
		}).catch((Error) => {
			reject(Error)
		});
	})
}


const getCategory = function() { // 获取菜单
	return new Promise((resolve, reject) => {
		db.collection('category').where({
			is_show: true
		}).orderBy('sort asc').field('_id,title,en_title,sort,is_show,goods_number,children,image').get().then(
			res => {
				resolve(res.result);
			}).catch((Error) => {
			reject(Error)
		});
	})
}

//  首页
const bannerImg = function() { // 获取轮播图
	return new Promise((resolve, reject) => {
		db.collection('banner').where({
			is_show: true
		}).field('image,is_show,url,sort,title').get().then(res => {
			resolve(res.result);
		}).catch((Error) => {
			reject(Error)
		});
	})
}
// 产品中心
const goods = function(options = {}) { // 获取菜单
	const {
		pageNum = 1, // 当前页码
			pageSize = 20, // 每页20条数据
			where = {}, // 默认无筛选条件
			orderByField = '', // 要查询的字段
			id = ''
	} = options;

	if (id) { // 商品详情
		return new Promise((resolve, reject) => {
			db.collection('goods').where({
				_id: id
			}).get({
				getOne: true
			}).then(res => {
				console.log(res.result)
				resolve(res.result);
			}).catch((Error) => {
				reject(Error)
			});
		})
	} else {
		where.is_shelf = true;
		return new Promise((resolve, reject) => {
			db.collection('goods')
				.orderBy('create_date', 'desc')
				.where(where)
				.skip((pageNum - 1) * pageSize)
				.limit(pageSize)
				.get({
					getCount: true
				}).then(res => {
					resolve(res.result);
				}).catch((Error) => {
					reject(Error)
				});
		})
	}

}

// 相关产品
const relatedGoods = function(options = {}, randomNumber) {
	const {
		id,
		_id,
		searchKeyword = '',
	} = options;
	let where = {};
	const filterSelf = _id ? {
		_id: {
			$ne: _id
		}
	} : {};
	if (searchKeyword && searchKeyword !== '') {
		where = {
			$and: [
				filterSelf, // 排除自身
				{
					is_shelf:true,
					$or: [{
							title: {
								$regex: searchKeyword,
								$options: 'i'
							}
						},
						{
							category: {
								$regex: searchKeyword,
								$options: 'i'
							}
						}
					],
					
					"is_shelf":true
				}
			]
		};
	} else {
		where = {
			$and: [
				filterSelf, // 排除自身
				{
					is_shelf:true,
					$or: [{
						category_id: id
					}]
				}
			]
		}
	}
	return new Promise((resolve, reject) => {
		const result = db.collection('goods')
			.orderBy('create_date', 'desc')
			.where(where)
			.get().then(res => {
				if (randomNumber && randomNumber > 0) {
					const allData = res.result.data;
					const shuffled = allData.sort(() => 0.5 - Math.random());
					const result = shuffled.slice(0, randomNumber);
					const filteredData = result.filter(item => item._id !== _id);
					resolve(filteredData);
				} else {
					let filteredData;
					if (_id) {
						filteredData = res.result.data.filter(item => item._id !== _id);
					} else {
						filteredData = res.result.data;
					}
					resolve(filteredData);
				}

			}).catch((Error) => {
				reject(Error)
			});
	})
};

// 添加购物车



// 订单中心
// 更新邮箱
const updateOrderEmail = function(orderId, newInvoice, newEmail) {
	return new Promise((resolve, reject) => {
		// 更新订单表中的邮箱信息
		db.collection('order')
			.where({
				_id: orderId // 假设使用_id作为订单唯一标识
			})
			.update({
				invoice: {
					...newInvoice,
				    // email: newEmail
				}
				// 如果需要保留invoice中的其他字段，使用以下方式
				// 'invoice.email': newEmail
			})
			.then(res => {
				if (res.updated === 0) {
					// 没有匹配到订单记录
					reject(new Error('未找到对应的订单或邮箱未变更'));
				} else {
					// 更新成功
					resolve({
						success: true,
						updated: res.updated,
						message: '邮箱更新成功'
					});
				}
			})
			.catch(error => {
				reject(error);
			});
	});
};

// 动态资讯

const getDataList = function(options = {}) { // 获取新闻
	const {
		page = 1, pageSize = 9, id = ''
	} = options;
	if (id) {
		return new Promise((resolve, reject) => {
			db.collection('news').where({
				_id: id._id
			}).get({
				getOne: true
			}).then(res => {
				console.log(res.result)
				resolve(res.result);
			}).catch((Error) => {
				reject(Error)
			});
		})
	} else {
		var skip = (page - 1) * 9;
		return new Promise((resolve, reject) => {
			db.collection('news').orderBy('create_date desc').skip(skip).limit(pageSize).get({
				getCount: true
			}).then(res => {
				console.log(res.result)
				resolve(res.result);
			}).catch((Error) => {
				reject(Error)
			});
		})
	}
}

// 新闻咨询封面图
const cover = function(options = {}) {
	const {
		news = 'news'
	} = options
	return new Promise((resolve, reject) => {
		db.collection('cover').where({
			type: news
		}).get().then(res => {
			resolve(res.result);
		}).catch(getErr => {
			console.error('获取资讯封面失败', getErr);
			reject(getErr);
		});
	});
}
// 点击量
const updateNewsClick = function(id) {
	return new Promise((resolve, reject) => {
		// 1. 先获取当前新闻的点击量
		db.collection('news').where({
			_id: id._id
		}).get({
			getOne: true
		}).then(res => {
			if (res.result) {
				console.log('获取点击量：', res.result.data)
				const currentClick = res.result.data.click || 0;
				const newClick = currentClick + 1;

				// 3. 更新点击量到数据库
				db.collection('news').where({
					_id: id._id
				}).update({
					click: newClick
				}).then(updateRes => {
					console.log('点击量更新成功', updateRes);
					resolve(updateRes);
				}).catch(updateErr => {
					console.error('点击量更新失败', updateErr);
					reject(updateErr);
				});
			} else {
				reject(new Error('未找到对应新闻'));
			}
		}).catch(getErr => {
			console.error('获取新闻信息失败', getErr);
			reject(getErr);
		});
	});
}

// 技术支持

// 关于工术

// 购物车

// 查询购物车数据
const cart = function(uid) {
	const where = {
		uid: uid,
	}; // 默认无筛选条件

	// .field(orderByField)
	return new Promise((resolve, reject) => {
		db.collection('cart')
			.orderBy('create_date', 'desc')
			.where(where)
			.get({
				getCount: true
			}).then(res => {
				resolve(res.result);
			}).catch((Error) => {
				reject(Error)
			});

		// const cartItem = db.collection('cart').doc('689d5af389bd277b76f2c903').get();

		// resolve(cartItem);
	})

}
// 查询购物车数量
const cartNumber = function(uid) {

	// .field(orderByField)

	return new Promise((resolve, reject) => {
		if (!uid) {
			resolve({
				totalN: 0
			})
		}
		db.collection('cart')
			.where({
				uid: uid
			})
			.get({
				getCount: true
			}).then((res) => {
				// 计算总数
				const totalN = res.result.data.reduce((total, item) => {
					return total + (item.param?.number || 0);
				}, 0);
				resolve({
					totalN: totalN
				})
			}).catch((err) => {
				reject(err)
			});
	})

}

// 批量删除购物车
const cartBatchDelete = function(uid, ids) {
	return new Promise((resolve, reject) => {
		// 参数验证
		if (!uid) {
			reject(new Error('用户标识不存在'));
			return;
		}

		if (!ids || !Array.isArray(ids) || ids.length === 0) {
			reject(new Error('请传入有效的id数组'));
			return;
		}

		// 执行批量删除，条件为：用户id匹配且记录id在传入的数组中
		const res = db.collection('cart').where({
			uid: uid,
			_id: db.command.in(ids) // 使用in查询操作符匹配多个id
		}).remove();

		res.then((res1) => {
			const n = cartNumber(uid)
			console.log('aaaa:::', n)
			resolve(n);
		}).catch((err) => {
			reject(err);
		});
	});
}
// 清空购物车
const cartClear = function(uid) { // 查询购物车数量
	return new Promise((resolve, reject) => {
		if (!uid) {
			throw new Error('用户标识不存在')
		}

		// 删除当前用户的所有购物车记录
		const res = db.collection('cart').where({
			uid: uid
		}).remove()
		res.then((res1) => {
			resolve(res1.result)
		}).catch((err) => {
			reject(err)
		})

	})

}
// 个人中心



export {
	getDataList,
	updateOrderEmail,
	updateNewsClick,
	cover,
	navigatorMenu,
	getCategory,
	bannerImg,
	goods,
	relatedGoods,
	cart,
	cartNumber,
	cartBatchDelete,
	cartClear
};